﻿using JiveMessenger.ImagePreview.Imgur;
using JiveMessenger.Utilities;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace JiveMessenger.ImagePreview.GfyCat
{
    internal static class GfyCatManager
    {
        internal const string GfyCatCheckUrl = "http://gfycat.com/cajax/checkUrl/";
        internal const string GfyCatGetUrl = "http://gfycat.com/cajax/get/";
        internal const string GfyCatConvertUrl = "http://upload.gfycat.com/transcodeRelease/";
        internal static GfyCatVideoFormat GfyCatVideoFormat { get; set; }
        internal static bool EnableGfyCat { get; set; }


        /// <summary>
        /// Get the GfyCat info for a .gif file.
        /// </summary>
        /// <param name="imageUrl"></param>
        /// <returns></returns>
        internal static GfyItem GetGfyItem(string imageUrl)
        {
            GfyItem item = null;

            GfyExists exists = CheckIfGfyExists(imageUrl);
            if (exists.urlKnown)
            {
                if (!String.IsNullOrEmpty(exists.gfyName))
                {
                    item = GetGfyItemForName(exists.gfyName);
                }
            }
            if (item == null)
                CreateGfyItem(imageUrl);



            return item;
        }

        internal static GfyItem GetGfyItemForName(string name)
        {
            TimeoutWebClient wc = new TimeoutWebClient(4000);
            string respons = wc.DownloadString(GfyCatGetUrl + name);
            return JsonConvert.DeserializeObject<GfyItemWrapper>(respons).gfyItem;
        }

        internal static GfyExists CheckIfGfyExists(string url)
        {
            TimeoutWebClient wc = new TimeoutWebClient(4000)
            {
                Proxy = null,
                Encoding = Encoding.UTF8
            };
            string encodedUrl = HttpUtility.UrlEncode(url);
            string gfyUrl = GfyCatCheckUrl + encodedUrl;
            return JsonConvert.DeserializeObject<GfyExists>(wc.DownloadString(gfyUrl));

        }


        internal static void CreateGfyItem(string url)
        {
            TimeoutWebClient wc = new TimeoutWebClient(9000)
            {
                Proxy = null,
                Encoding = Encoding.UTF8
            };
            string encodedUrl = HttpUtility.UrlEncode(url);
            var r = new Random();
            ////Random IP Address
            //wc.Headers["X-Forwarded-For"] = r.Next(0, 255) + "." + r.Next(0, 255) + "." + r.Next(0, 255) + "." + r.Next(0, 255);
            ////Random User-Agent
            //wc.Headers["User-Agent"] = "Mozilla/" + r.Next(3, 5) + ".0 (Windows NT " + r.Next(3, 5) + "." + r.Next(0, 2) + "; rv:2.0.1) Gecko/20100101 Firefox/" + r.Next(3, 5) + "." + r.Next(0, 5) + "." + r.Next(0, 5);
            string gfyUrl = string.Format("{0}{1}?fetchurl={2}", GfyCatConvertUrl, r.Next(10000, 99999999), encodedUrl);
            wc.DownloadStringCompleted += (s, e) =>
            {
                GfyCreateResponse response = JsonConvert.DeserializeObject<GfyCreateResponse>(e.Result);
                if (response.GfyName != null)
                {

                }
            };
            wc.DownloadStringAsync(new Uri(gfyUrl, UriKind.Absolute), url);
        }

        internal static GfyLink GetGfyCatLink(string url)
        {
            Regex imgRegex = new Regex(@"gfycat\.com/(\w+)(/.*\z|/.*\.gif)?", RegexOptions.IgnoreCase);
            Match imgMatch = imgRegex.Match(url);
            if (imgMatch.Success)
            {
                return new GfyLink(imgMatch.Groups[1].Value, url);
            }
            return null;
        }
        internal static string GetVideoUrlForGfyItem(GfyItem item)
        {
            switch (GfyCatVideoFormat)
            {
                default:
                case GfyCatVideoFormat.mp4:
                    return item.mp4Url;
                case  GfyCatVideoFormat.WebM:
                    return item.webmUrl;
            }
        }

        //public static T StringToObject<T>(string input)
        //{
        //    if (String.IsNullOrEmpty(input))
        //        return default(T);
        //    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(input)))
        //    {
        //       System.Runtime.Serialization. DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        //        return (T)ser.ReadObject(stream);
        //    }
        //}
    }
}
